<template>
	<div class="sw_tinymce_editor">
		<textarea ref="editorArea" v-model="editorContent"></textarea>
	</div>
</template>

<script>
import editoConfig from './config';
import toolbarConfig from './toolbar';
import emitter from 'element-ui/src/mixins/emitter';
export default {
	name: 'swTinyEditor',
	mixins: [emitter],
	props: {
		value: { type: String, default: '' },
		blank: { type: Boolean, default: false },
		type: { type: String, default: 'question' },
		height: { type: [Number, String], default: 112 },
		disabled: { type: Boolean, default: false }
	},
	data() {
		return {
			tinymceInstance: null,
			editorContent: this.value
		};
	},
	watch: {
		value(val) {
			if (val !== this.editorContent) {
				this.editorContent = val;
				this.updateEditorContent();
			}
		},
		editorContent(val) {
			this.$emit('input', val);
			this.dispatch('ElFormItem', 'el.form.change', [val]);
		},
		blank(flag) {
			this.tinymceInstance.settings['blank'] = flag;
		}
	},
	mounted() {
		this.initTinymce();
	},
	destroyed() {
		if (this.tinymceInstance) {
			this.tinymceInstance.destroy();
		}
	},
	methods: {
		initTinymce() {
			let target = this.$refs['editorArea'];
			let editorOption = {
				height: this.height,
				toolbar: toolbarConfig(this.type),
				images_upload_handler: this.imageUploadHandler,
				delete_highlight_handler: (editer, key) => {
					this.$emit('delete', key);
				}
			};
			new editoConfig(target, editorOption, (editor) => {
				this.tinymceInstance = editor;
				editor.on('blur', () => this.cleanEmptyTags(editor));
				editor.on('input', () => {
					this.editorContent = editor.getContent();
				});
			});
		},
		updateEditorContent() {
			if (!!this.tinymceInstance) {
				let content = this.$removeEmptyTag(this.editorContent);
				this.tinymceInstance.setContent(content);
			}
		},
		handleInsertText(key) {
			this.tinymceInstance.execCommand('insertHighlightBlock', false, { key });
		},
		handleDeleteBlock(key) {
			this.tinymceInstance.execCommand('deleteHighlightBlock', false, { key });
		},
		cleanEmptyTags(editor) {
			let parser = new DOMParser();
			let html = editor.getContent();
			let doc = parser.parseFromString(html, 'text/html');
			const isEmptyNode = (content, html) => {
				let isEmpty = content === '' && html === '';
				let isNbsp = content === '' && html === '&nbsp;';
				return isEmpty || isNbsp || html.match(/^<br\s*\/?>$/i);
			};
			const cleanNode = (node) => {
				for (let i = node.childNodes.length - 1; i >= 0; i--) {
					let child = node.childNodes[i];
					cleanNode(child);
					if (child.nodeType === 1) {
						let innerHTML = child.innerHTML.trim();
						let textContent = child.textContent.trim();
						isEmptyNode(textContent, innerHTML) && node.removeChild(child);
					}
				}
			};
			if (!html) return false;
			cleanNode(doc.body);
			editor.setContent(doc.body.innerHTML);
		},

		//图片上传处理
		imageUploadHandler(blobInfo, success, failure) {
			let reader = new FileReader();
			reader.onload = (e) => {
				let previewSrc = e.target.result;
				let filename = blobInfo.filename(); // 原文件名
				// 将预览图插入编辑器（临时显示）
				let imgHtml = `<img src="${previewSrc}" alt="${filename}" data-mce-src="${previewSrc}" />`;
				this.tinymceInstance.insertContent(imgHtml);
				// success(previewSrc);
			};
			reader.readAsDataURL(blobInfo.blob());
		}
	}
};
</script>

<style lang="scss" scoped>
.sw_tinymce_editor::v-deep {
	position: relative;
	border-radius: 4px;
	border: 1px solid #dcdfe6;
	box-sizing: border-box;
	overflow: hidden;
	width: 100%;
	textarea {
		display: none;
	}
	.tox-tinymce {
		border: none;
	}
}
</style>
